package com.demo.zyt.modules.sys.oauth2;

import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

/**
 * 认证
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-05-20 14:00
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {
	

	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof OAuth2Token;
	}

	/**
	 * 授权(验证权限时调用)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//		SubjectEntity subjectEntity = (SubjectEntity) principals.getPrimaryPrincipal();
//		String userId = subjectEntity.getUser().getUserId();
//
//		// 用户权限列表
//		Set<String> permsSet = shiroService.getUserPermissions(userId);
		Set<String> permsSet = null;

		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(permsSet);
		return info;
	}

	/**
	 * 认证(登录时调用)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//		String accessToken = (String) token.getPrincipal();
//
//		// 根据accessToken，查询用户信息
//		SysUserTokenEntity tokenEntity = shiroService.queryByToken(accessToken);
//		// token失效
//		if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
//			throw new IncorrectCredentialsException("token失效，请重新登录");
//		}
//
//		SubjectEntity entity = new SubjectEntity();
//
//		// 查询用户信息
//		EimsSysUserEntity user = shiroService.queryUser(tokenEntity.getUserId());
//		entity.setUser(user);
//
//		// 保存当前企业信息
//		List<EmployeeDTO> orgWithDept = eimsOrganizationService.selectOrgWithDeptByUserId(tokenEntity.getUserId());
//		for (EmployeeDTO org : orgWithDept) {
//			if (org.getOrgId().equals(tokenEntity.getOrgId())) {
//				EntityWrapper<EimsEmployeeEntity> wrapper = new EntityWrapper<>();
//				wrapper.eq("dept_id", org.getDeptId());
//				wrapper.eq("user_id", user.getUserId());
//				EimsEmployeeEntity employee = eimsEmployeeService.selectOne(wrapper);
//				org.setEmployeeId(employee.getEmployeeId());
//				entity.setOrg(org);
//			}
//		}
//
//		// 账号锁定
//		if (Integer.valueOf(user.getStatus()).intValue() == CommonParameters.USER_STATUS.LOCK.intValue()) {
//			throw new LockedAccountException("账号已被锁定,请联系管理员");
//		}
//
//		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(entity, accessToken, getName());
//		return info;
		return null;
	}
}
